//
//  CommentView.m
//  Bespoke
//
//  Created by Cheng on 12/10/27.
//
//

#import "CommentView.h"
#import "DetailViewController.h"
#import "RequestAPIFunction.h"
#import "CommentCell.h"

#define KEYBOARDHEIGHT 350
#define Comment_Tag 5000
#define CommentAndUser_SPACE 500
#define BETWEEN_TITLE_AND_COMMENT 20
#define Content_SPACE 10
#define SCROLLVIEW_AXIS_Y 170

#define COMMENT_ARROW_AXIS_X 104
#define DEFAULT_COMMENT_CELL_HEIGHT 85
#define DEFAULT_COMMENT_CELL_AXIS_X 230
#define COMMENT_CELL_CONTENT_WIDTH 305
#define COMMENT_CELL_CONTENT_HEIGHT_MAXIMUM 300
#define DEFAULT_CONTENT @"Write your comment here."

#define NEW_YORK_GMT -5
#define SECOND 1
#define MINUTE (60 * SECOND)
#define HOUR (60 * MINUTE)
#define DAY (24 * HOUR)
#define MONTH (30 * DAY)

#define COMMENT_API @"http://54.235.166.43/BeSpokeAPI/Comment/Upload.php"

@implementation CommentView
@synthesize TVw_AddContent, SVw_Content, IVw_AccountPhoto, Lab_FullName;
@synthesize MLM_Detail, BK_En_object, MLM_Detail_InBook;
@synthesize delegate;

- (IBAction)CancelPressed:(id)sender {
    [self.delegate uiViewTouched_Comment:NO];
}

- (void)initialize {
    
    int Content_AxisY = DEFAULT_COMMENT_CELL_AXIS_X;
    
    //Default.
    CGSize maximumLabelSize = CGSizeMake(COMMENT_CELL_CONTENT_WIDTH, COMMENT_CELL_CONTENT_HEIGHT_MAXIMUM);
    UIColor *Cyan = [UIColor colorWithRed:189.0/255.0 green:228.0/255.0 blue:229.0/255.0 alpha:1.0];
    int Cell_Height;
    
    //Add Comment to ScrollView
    for (MediaListsComment *Comment in [MLM_Detail.Array_Comment reverseObjectEnumerator]) {
        
        //Init Cell.
        CommentCell *Vw_CommentCell = [[[NSBundle mainBundle] loadNibNamed:@"CommentCell" owner:self options:nil] objectAtIndex: 0];
        Vw_CommentCell.Lab_FullName.textColor = Cyan;
        Vw_CommentCell.Lab_FullName.text = [Comment.NS_UserName uppercaseString];
        Vw_CommentCell.Lab_Content.text = Comment.NS_Content;
        Vw_CommentCell.ND_Date = Comment.ND_Date;
        
        //Adjust Content Size.
        CGSize Size_User = [Vw_CommentCell.Lab_Content.text
                            sizeWithFont:Vw_CommentCell.Lab_Content.font
                            constrainedToSize:maximumLabelSize
                            lineBreakMode:NSLineBreakByTruncatingTail];
        Vw_CommentCell.Lab_Content.frame = CGRectMake(Vw_CommentCell.Lab_Content.frame.origin.x,
                                                      Vw_CommentCell.Lab_Content.frame.origin.y,
                                                      Vw_CommentCell.Lab_Content.frame.size.width,
                                                      Size_User.height);
        
        //Check Content Size over Cell frame.
        if (DEFAULT_COMMENT_CELL_HEIGHT>Vw_CommentCell.Lab_Content.frame.origin.y+Size_User.height)
            Cell_Height = DEFAULT_COMMENT_CELL_HEIGHT;
        else
            Cell_Height = Vw_CommentCell.Lab_Content.frame.origin.y+Size_User.height;
            
        Vw_CommentCell.frame = CGRectMake(0, Content_AxisY, Vw_CommentCell.frame.size.width, Cell_Height);
            
        [SVw_Content addSubview:Vw_CommentCell];
        
        Content_AxisY = Content_AxisY + Vw_CommentCell.frame.size.height +Content_SPACE;
    }
    
    Lab_FullName.text = [self.BK_En_object.fullName uppercaseString];
    
    [self.IVw_AccountPhoto setImage:self.BK_En_object.yourPhoto];
    
    [SVw_Content setContentSize:CGSizeMake(0, Content_AxisY-Content_SPACE)];
}

- (void)CalculateDateTime {
    
    for (CommentCell *Temp_Cell in SVw_Content.subviews)
        if ([Temp_Cell isKindOfClass:[CommentCell class]])
            Temp_Cell.Lab_TimeAgo.text = [self timeIntervalWithStartDate:Temp_Cell.ND_Date
                                                             withEndDate:[NSDate dateWithTimeIntervalSinceNow:+(NEW_YORK_GMT*HOUR)]];
}

- (IBAction)DonePressed:(id)sender {
    
    if (([TVw_AddContent.text isEqualToString:@""])||(TVw_AddContent.textColor==[UIColor lightGrayColor])) {
        
        UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please enter a text." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [AlertView show];
        return;
    }
    
    self.frame = CGRectMake(((DetailViewController *)self.delegate).Bt_AddComment.center.x-COMMENT_ARROW_AXIS_X,
                            ((DetailViewController *)self.delegate).Bt_AddComment.frame.origin.y-self.frame.size.height,
                            self.frame.size.width,
                            self.frame.size.height);
    
    [self.TVw_AddContent resignFirstResponder];
    
    NSData *responseData =
    [RequestAPIFunction XML_PostRequest:[NSString stringWithFormat:@"<Comment Id=\"\" Content=\"%@\" MediaId=\"%d\" User=\"%@\" lastUpdate=\"%@\"/>",
                                  TVw_AddContent.text,
                                  MLM_Detail.MediaID,
                                  BK_En_object.userName,
                                  [NSDate dateWithTimeIntervalSinceNow:+(NEW_YORK_GMT*HOUR)]       
                                  ] urlString:COMMENT_API];
    
    //No Network Connection or time out.
    if (responseData == nil)
        return;
    
    NSError *error;
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:responseData options:0 error:&error];
    
    //Check to upload is success.
    if ([[doc nodesForXPath:@"//Success" error:&error] count]!=0) {
        
        int CommentId = [[[[[doc nodesForXPath:@"//Success" error:nil] objectAtIndex:0] attributeForName:@"CommentId"] stringValue] integerValue];
        
        MediaListsComment *MLC_Comment = [[MediaListsComment alloc] init:CommentId
                                                              SetContent:TVw_AddContent.text
                                                             SetUserName:BK_En_object.fullName
                                                                 SetDate:[NSDate dateWithTimeIntervalSinceNow:+(NEW_YORK_GMT*HOUR)]];
        
        [MLM_Detail.Array_Comment addObject:MLC_Comment];
        
        //Check Media is in Mybook.
        if (MLM_Detail_InBook!=nil)
            [MLM_Detail_InBook.Array_Comment addObject:MLC_Comment];
        
        
        [((DetailViewController *)self.delegate).Bt_Comment setTitle:[NSString stringWithFormat:@"%d",MLM_Detail.Array_Comment.count] forState:UIControlStateNormal];
    
        //Default.
        CGSize maximumLabelSize = CGSizeMake(COMMENT_CELL_CONTENT_WIDTH, 300);
        UIColor *Cyan = [UIColor colorWithRed:189.0/255.0 green:228.0/255.0 blue:229.0/255.0 alpha:1.0];
        int Cell_Height;
        
        //Init Cell.
        CommentCell *Vw_CommentCell = [[[NSBundle mainBundle] loadNibNamed:@"CommentCell" owner:self options:nil] objectAtIndex: 0];
        Vw_CommentCell.Lab_FullName.textColor = Cyan;
        Vw_CommentCell.Lab_FullName.text = [BK_En_object.fullName uppercaseString];
        Vw_CommentCell.Lab_Content.text = TVw_AddContent.text;
        Vw_CommentCell.ND_Date = [NSDate dateWithTimeIntervalSinceNow:+(NEW_YORK_GMT*HOUR)];
        Vw_CommentCell.IVw_AccountPhoto.image = BK_En_object.yourPhoto;
        
        //Adjust Content Size.
        CGSize Size_User = [Vw_CommentCell.Lab_Content.text
                            sizeWithFont:Vw_CommentCell.Lab_Content.font
                            constrainedToSize:maximumLabelSize
                            lineBreakMode:NSLineBreakByTruncatingTail];
        Vw_CommentCell.Lab_Content.frame = CGRectMake(Vw_CommentCell.Lab_Content.frame.origin.x,
                                                      Vw_CommentCell.Lab_Content.frame.origin.y,
                                                      Vw_CommentCell.Lab_Content.frame.size.width,
                                                      Size_User.height);
        
        //Check Content Size over Cell frame.
        if (DEFAULT_COMMENT_CELL_HEIGHT>Vw_CommentCell.Lab_Content.frame.origin.y+Size_User.height)
            Cell_Height = DEFAULT_COMMENT_CELL_HEIGHT;
        else
            Cell_Height = Vw_CommentCell.Lab_Content.frame.origin.y+Size_User.height;
        
        Vw_CommentCell.frame = CGRectMake(0, DEFAULT_COMMENT_CELL_AXIS_X, Vw_CommentCell.frame.size.width, Cell_Height);
        
        //Animation.
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.5];
        [UIView setAnimationBeginsFromCurrentState:YES];
        
        int Scroll_Height = Vw_CommentCell.frame.origin.y+Vw_CommentCell.frame.size.height;
        
        //Search Cells.
        for (CommentCell *Temp_Cell in SVw_Content.subviews)
            if ([Temp_Cell isKindOfClass:[CommentCell class]]) {
                Temp_Cell.frame = CGRectMake(0,
                                             Temp_Cell.frame.origin.y+Cell_Height,
                                             Temp_Cell.frame.size.width,
                                             Temp_Cell.frame.size.height);
                
                Temp_Cell.Lab_TimeAgo.text = [self timeIntervalWithStartDate:Temp_Cell.ND_Date
                                                                 withEndDate:[NSDate dateWithTimeIntervalSinceNow:+(NEW_YORK_GMT*HOUR)]];
                
                Scroll_Height = Scroll_Height+Temp_Cell.frame.size.height;
            }
        
        [SVw_Content addSubview:Vw_CommentCell];
        
        [SVw_Content setContentSize:CGSizeMake(0, Scroll_Height)];
        
        NSLog(@"%d",Scroll_Height);
        [UIView commitAnimations];
        
        //Default Content.
        TVw_AddContent.text = DEFAULT_CONTENT;
        TVw_AddContent.textColor = [UIColor lightGrayColor];
        
    }
}

#pragma mark - UITextViewDelegate

- (void)textViewDidBeginEditing:(UITextView *)textView {
    
    self.frame = CGRectMake(self.frame.origin.x,  0, self.frame.size.width, self.frame.size.height);
    
    if ([textView.text isEqualToString:DEFAULT_CONTENT])
        textView.text = @"";
    textView.textColor = [UIColor blackColor];
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    
    self.frame = CGRectMake(((DetailViewController *)self.delegate).Bt_AddComment.center.x-COMMENT_ARROW_AXIS_X,
                            ((DetailViewController *)self.delegate).Bt_AddComment.frame.origin.y-self.frame.size.height,
                            self.frame.size.width,
                            self.frame.size.height);
    
    if(textView.text.length == 0){
        textView.textColor = [UIColor lightGrayColor];
        textView.text = DEFAULT_CONTENT;
        [textView resignFirstResponder];
    }
}

#pragma mark - days ago

- (NSString*)timeIntervalWithStartDate:(NSDate*)d1 withEndDate:(NSDate*)d2
{
    //Calculate the delta in seconds between the two dates
    NSTimeInterval delta = [d2 timeIntervalSinceDate:d1];
    
    if (delta < 1 * MINUTE)
    {
        return delta == 1 ? @"one second ago" : [NSString stringWithFormat:@"%d seconds ago", (int)delta];
    }
    if (delta < 2 * MINUTE)
    {
        return @"a minute ago";
    }
    if (delta < 45 * MINUTE)
    {
        int minutes = floor((double)delta/MINUTE);
        return [NSString stringWithFormat:@"%d minutes ago", minutes];
    }
    if (delta < 90 * MINUTE)
    {
        return @"an hour ago";
    }
    if (delta < 24 * HOUR)
    {
        int hours = floor((double)delta/HOUR);
        return [NSString stringWithFormat:@"%d hours ago", hours];
    }
    if (delta < 48 * HOUR)
    {
        return @"yesterday";
    }
    if (delta < 30 * DAY)
    {
        int days = floor((double)delta/DAY);
        return [NSString stringWithFormat:@"%d days ago", days];
    }
    if (delta < 12 * MONTH)
    {
        int months = floor((double)delta/MONTH);
        return months <= 1 ? @"one month ago" : [NSString stringWithFormat:@"%d months ago", months];
    }
    else
    {
        int years = floor((double)delta/MONTH/12.0);
        return years <= 1 ? @"one year ago" : [NSString stringWithFormat:@"%d years ago", years];
    }
}

#pragma mark - Touches

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    if( point.x > 0 && point.x < self.frame.size.width && point.y > 0 && point.y < self.frame.size.height )
    {
        [self.delegate uiViewTouched_Comment:YES];
        return YES;
    }
    
    [self.delegate uiViewTouched_Comment:NO];
    return NO;
}

@end
